package com.ruoyi.framework.security.service;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.RegisterLogin;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.RegisterBody;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysUserService;

import javax.annotation.Resource;

/**
 * 注册校验方法
 *
 */
@Component
public class SysRegisterService {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 注册
     */
    public RegisterLogin register(RegisterBody registerBody) {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(registerBody.getNickname());
        sysUser.setStatus("1"); // 自主注册默认不启用
        sysUser.setParent(registerBody.getParent()); // 自主注册默认不启用
        boolean captchaEnabled = configService.selectCaptchaEnabled();  // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(registerBody);
        }
        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        } else if (!userService.checkUserNameUnique(sysUser)) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
                // 用户验证
                Authentication authentication;
                try {
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
                    AuthenticationContextHolder.setContext(authenticationToken);
                    // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
                    authentication = authenticationManager.authenticate(authenticationToken);
                } catch (Exception e) {
                    if (e instanceof BadCredentialsException) {
                        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                        throw new UserPasswordNotMatchException();
                    } else {
                        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                        throw new ServiceException(e.getMessage());
                    }
                } finally {
                    AuthenticationContextHolder.clearContext();
                }
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                sysLoginService.recordLoginInfo(loginUser.getUserId());
                // 生成token
                return new RegisterLogin(true, tokenService.createToken(loginUser));
            }
        }
        return new RegisterLogin(false, msg);
    }

    /**
     * 校验验证码
     *
     * @param registerBody
     * @return 结果
     */
    public void validateCaptcha(RegisterBody registerBody) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + registerBody.getUuid();
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!registerBody.getCode().equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }
}
